#include <stdio.h>
#include <curl/curl.h>
#include <malloc.h>
#include <string.h>

char output_buffer[8091];
int output_offset;

size_t read_func(void *ptr,size_t size,size_t numb,void *stream)
{
	memcpy(output_buffer + output_offset, ptr, numb);
	output_offset += numb;
	return numb;
}


char *shorten_link(const char *link,const char *login,const char *api_key)
{
	CURL *curl = curl_easy_init();
	char buffer[4048];
	buffer[0] = 0;
	strcat(buffer,"http://api.bit.ly/shorten?version=2.0.1&longUrl=");
	strcat(buffer,curl_escape(link,strlen(link)));
	strcat(buffer,"&login=");
	strcat(buffer,curl_escape(login,strlen(login)));
	strcat(buffer,"&apiKey=");
	strcat(buffer,curl_escape(api_key,strlen(api_key)));

	curl_easy_setopt(curl,CURLOPT_URL,buffer);
	curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION, read_func);
	output_offset = 0;
	curl_easy_perform(curl);
	output_buffer[output_offset] = 0;

	char *temp = strstr(output_buffer,"\"shortUrl\":") + 13;
	temp[strchr(temp,'\"') - temp] = 0;
	curl_easy_cleanup(curl);	
	return temp;
}

char *expand_link(const char *link,const char *login,const char *api_key)
{
	CURL *curl = curl_easy_init();
	char buffer[4048];
	buffer[0] = 0;
	strcat(buffer,"http://api.bit.ly/expand?version=2.0.1&shortUrl=");
	strcat(buffer,curl_escape(link,strlen(link)));
	strcat(buffer,"&login=");
	strcat(buffer,curl_escape(login,strlen(login)));
	strcat(buffer,"&apiKey=");
	strcat(buffer,curl_escape(api_key,strlen(api_key)));

	curl_easy_setopt(curl,CURLOPT_URL,buffer);
	curl_easy_setopt(curl,CURLOPT_WRITEFUNCTION, read_func);
	output_offset = 0;
	curl_easy_perform(curl);
	output_buffer[output_offset] = 0;

	char *temp = strstr(output_buffer,"\"longUrl\":") + 12;
	temp[strchr(temp,'\"') - temp] = 0;
	curl_easy_cleanup(curl);	
	return temp;
}
